Scroll Progress Bar

Nested While Loop

A nested while loop is a while loop that is placed inside another while loop. It allows repeatedly executing a set of code within the outer loop and, for each iteration of the outer loop, executing the inner loop multiple times.

Here's a C program demonstrating a nested while loop with comments:


#include <stdio.h>

int main() {
    int outer_count = 1; // Initialize the outer loop counter

    while (outer_count <= 3) { // Outer loop runs 3 times
        printf("Outer loop iteration: %d\n", outer_count);

        int inner_count = 1; // Initialize the inner loop counter

        while (inner_count <= 4) { // Inner loop runs 4 times
            printf("Inner loop iteration: %d\n", inner_count);
            inner_count++; // Increment the inner loop counter
        }

        outer_count++; // Increment the outer loop counter
    }

    return 0;
}
Explanation:
  • In this program, an outer while loop and an inner while loop.
  • The outer loop is responsible for printing "Outer loop iteration" and runs three times (when outer_count is 1, 2, and 3).
  • The inner loop is responsible for printing "Inner loop iteration" and runs four times (when inner_count is 1, 2, 3, and 4) for each iteration of the outer loop.
  • The outer loop counter outer_count starts at 1 and increments by 1 in each iteration until it becomes 4, which causes the outer loop to terminate.
  • The inner loop counter inner_count starts at 1 for each outer loop iteration and increments by 1 in each iteration until it becomes 5, which causes the inner loop to terminate and moves to the next iteration of the outer loop.
Sample Output:

Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4
Outer loop iteration: 3
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Inner loop iteration: 4

In the output, the iterations of both the outer loop and the inner loop. The inner loop runs four times for each iteration of the outer loop, demonstrating the nested behaviour of the while loops.


What is a nested while loop in C?


Nested

What does a nested while loop contain?


Another

What is the purpose of using nested while loops in C?


Complex